package com.ouc.dataMange.controller;

import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.ouc.common.config.OUCAjaxResult;
import com.ouc.common.utils.DateUtils;
import com.ouc.common.utils.file.FileUtils;
import com.ouc.dataMange.domain.SysDataElectronicChart;
import com.ouc.dataMange.service.ISysDataSetService;
import com.ouc.dataMange.service.ISysMemoryDeviceService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ouc.common.annotation.Log;
import com.ouc.common.core.controller.BaseController;
import com.ouc.common.core.domain.AjaxResult;
import com.ouc.common.enums.BusinessType;
import com.ouc.dataMange.domain.SysEddyFile;
import com.ouc.dataMange.service.ISysEddyFileService;
import com.ouc.common.utils.poi.ExcelUtil;
import com.ouc.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * SysEddyFileController
 *
 * @author ouc
 * @date 2025-07-28
 */
@RestController
@RequestMapping("/dataMange/eddyFile")
public class SysEddyFileController extends BaseController {
  @Autowired
  private ISysEddyFileService sysEddyFileService;

  @Autowired
  private ISysMemoryDeviceService memoryDeviceService;

  @Autowired
  private ISysDataSetService dataSetService;

  /**
   * 查询SysEddyFile列表
   */
//    @PreAuthorize("@ss.hasPermi('dataMange:eddyFile:list')")
  @GetMapping("/list")
  public TableDataInfo list(SysEddyFile sysEddyFile) {
    startPage();
    List<SysEddyFile> list = sysEddyFileService.selectSysEddyFileList(sysEddyFile);
    return getDataTable(list);
  }

  /**
   * 导出SysEddyFile列表
   */
  @PreAuthorize("@ss.hasPermi('dataMange:eddyFile:export')")
  @Log(title = "SysEddyFile", businessType = BusinessType.EXPORT)
  @PostMapping("/export")
  public void export(HttpServletResponse response, SysEddyFile sysEddyFile) {
    List<SysEddyFile> list = sysEddyFileService.selectSysEddyFileList(sysEddyFile);
    ExcelUtil<SysEddyFile> util = new ExcelUtil<SysEddyFile>(SysEddyFile.class);
    util.exportExcel(response, list, "SysEddyFile数据");
  }

  /**
   * 获取SysEddyFile详细信息
   */
  @PreAuthorize("@ss.hasPermi('dataMange:eddyFile:query')")
  @GetMapping(value = "/{fileId}")
  public AjaxResult getInfo(@PathVariable("fileId") Integer fileId) {
    return success(sysEddyFileService.selectSysEddyFileByFileId(fileId));
  }

  /**
   * 新增SysEddyFile
   */
  @PreAuthorize("@ss.hasPermi('dataMange:eddyFile:add')")
  @Log(title = "SysEddyFile", businessType = BusinessType.INSERT)
  @PostMapping
  public AjaxResult add(@RequestBody SysEddyFile sysEddyFile) {
    return toAjax(sysEddyFileService.insertSysEddyFile(sysEddyFile));
  }

  /**
   * 修改SysEddyFile
   */
  @PreAuthorize("@ss.hasPermi('dataMange:eddyFile:edit')")
  @Log(title = "SysEddyFile", businessType = BusinessType.UPDATE)
  @PutMapping
  public AjaxResult edit(@RequestBody SysEddyFile sysEddyFile) {
    return toAjax(sysEddyFileService.updateSysEddyFile(sysEddyFile));
  }

  /**
   * 删除SysEddyFile
   */
  @PreAuthorize("@ss.hasPermi('dataMange:eddyFile:remove')")
  @Log(title = "SysEddyFile", businessType = BusinessType.DELETE)
  @DeleteMapping("/{fileIds}")
  public AjaxResult remove(@PathVariable Integer[] fileIds) {
    return toAjax(sysEddyFileService.deleteSysEddyFileByFileIds(fileIds));
  }

  /**
   * 上传文件
   */
  @ResponseBody
  @RequestMapping("/uploadEddyFile")
  public OUCAjaxResult uploadEddyFile(MultipartFile file,
                                      @RequestParam(value = "userName", required = false, defaultValue = "admin") String userName,
                                      @RequestParam(value = "userId", required = false, defaultValue = "1") Integer userId,
                                      @RequestParam(value = "dataSetId", required = false, defaultValue = "7") Integer dataSetId,
                                      @RequestParam(value = "memoryId", required = false, defaultValue = "10") Integer memoryId) throws Exception {
    String[] fileSplit = file.getOriginalFilename().split("/");
    String fileDir = memoryDeviceService.selectSysMemoryDeviceById(memoryId).getSysMemoryDevice()
        + dataSetService.selectSysDataSetById(dataSetId).getDataSetDevice() + File.separator;
    File newFile = new File(fileDir);
    if (!newFile.exists()) {
      newFile.mkdirs();
    }
    String fileName = fileSplit[fileSplit.length - 1];
    file.transferTo(new File(fileDir, fileName));


    SysEddyFile eddyFile = new SysEddyFile();
    eddyFile.setUserId(userId);
    eddyFile.setUserName(userName);
    eddyFile.setUploadTime(DateUtils.getNowDate());
    eddyFile.setFilePath(File.separator + fileName);
    eddyFile.setDataMemoryId(memoryId);
    eddyFile.setDataSetId(dataSetId);
    eddyFile.setViewTime(DateUtils.getNowDate());
    eddyFile.setViewNum(1);
    eddyFile.setUploadNum(0);
    sysEddyFileService.insertSysEddyFile(eddyFile);

    return OUCAjaxResult.ok(fileDir + fileName);
  }

  /**
   * 涡旋下载excel
   */
  @ResponseBody
  @RequestMapping("/download")
  public AjaxResult download(HttpServletResponse response, Integer fileId) {
    try {
      SysEddyFile eddyFile = sysEddyFileService.selectSysEddyFileByFileId(fileId);
      String filePath = memoryDeviceService.selectSysMemoryDeviceById(eddyFile.getDataMemoryId()).getSysMemoryDevice()
          + dataSetService.selectSysDataSetById(eddyFile.getDataSetId()).getDataSetDevice() + eddyFile.getFilePath();
      if (!new File(filePath).exists()) {
        return AjaxResult.error("文件不存在，请重试");
      }
      File file = new File(filePath);
      response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));//文件下载
//      response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName,"UTF-8"));//文件预览

      ServletOutputStream outputStream = response.getOutputStream();
      outputStream.write(FileUtils.getFileByteArray(file));//把文件的字节数写出去
      outputStream.flush();//刷新一下
      outputStream.close();//一定要关闭文件流

      SysEddyFile update = new SysEddyFile();
      update.setFileId(fileId);
      update.setUploadNum(eddyFile.getUploadNum() + 1);
      sysEddyFileService.updateSysEddyFile(update);

      return AjaxResult.success("文件下载成功");
    } catch (Exception e) {
      return AjaxResult.error(e.toString());
    }
  }

  /**
   * 数据统计
   */
  @ResponseBody
  @RequestMapping("/dataStatistics")
  public OUCAjaxResult dataStatistics() {
    Map<String, Integer> result = new HashMap<>();
    List<SysEddyFile> list = sysEddyFileService.selectSysEddyFileList(null);
    result.put("数据个数", list.size());
    Integer dataSize = 0;
    Integer fileNum = 0;
    for (SysEddyFile eddyFile : list) {
      String filePath = memoryDeviceService.selectSysMemoryDeviceById(eddyFile.getDataMemoryId()).getSysMemoryDevice()
          + dataSetService.selectSysDataSetById(eddyFile.getDataSetId()).getDataSetDevice() + eddyFile.getFilePath();
      File file = new File(filePath);
      dataSize += (int) file.length() / (1024 * 1024) + 1;
    }
    result.put("数据所占空间", dataSize);
    return OUCAjaxResult.ok(result);
  }

}
